package com.ruoyi.framework.scheduling;

import com.ruoyi.system.config.properties.EmailVerificationCodeProperties;
import com.ruoyi.system.dto.DeserializableMailMessage;
import com.ruoyi.system.service.ISysEmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 定时发送邮件
 *
 * @author 刘逸晖
 */
@Component
public class SendEmailScheduling {

    /**
     * 访问 Redis
     */
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 邮件验证码相关配置
     */
    @Autowired
    private EmailVerificationCodeProperties emailVerificationCodeProperties;

    /**
     * 处理邮件相关业务
     */
    @Autowired
    private ISysEmailService emailService;

    /**
     * 发送邮件的定时任务
     *
     * @throws InterruptedException
     */
    @Scheduled(cron = "${ruoyi.verification-code.email.tasksCycle}")
    public void send() throws InterruptedException {
        Object value = this.redisTemplate.opsForSet().pop(this.emailVerificationCodeProperties.getTasksKey());

        while (value instanceof DeserializableMailMessage) {
            this.emailService.send((DeserializableMailMessage) value);

            value = this.redisTemplate.opsForSet().pop(this.emailVerificationCodeProperties.getTasksKey());
        }
    }

}
